import random
import time

from django.http import HttpResponse
from django.shortcuts import render, redirect

# Create your views here.
from django.urls import reverse
from django.views import View

from mock.forms import ServeraddForm, EditServerForm, RouteraddForm, ResponseaddForm, EditRouterForm
from mock.models import Server, Api_Route, Response
from util.util_tools import isTextEmpty


def createJsonReponse(text):
    return HttpResponse(text,content_type='application/json;charset=utf-8')


def search(request):
    server_name = request.GET.get('server_nam')
    error_msg = ''

    if not server_name:
        error_msg = '请输入关键词'
        return render(request,'mock/errors.html',{'error_msg':error_msg})

    server_list = Server.objects.filter(name__icontains=server_name)
    return render(request,'mock/seresult.html',{'error_msg':error_msg,'server_list':server_list})
class Mock_server(View):
    # self 内参数
    # def get(self,*args,**kwargs):
    #     server = self.kwargs['api_server']
    #     router = self.kwargs['api_router']


    def get(self,request,api_server,api_router):
        # 判断请求地址正确性
        if isTextEmpty(api_server) or isTextEmpty(api_router):
            return createJsonReponse('请确保请求地址正确')

        # 检查server
        server_list = Server.objects.filter(path=api_server)
        if len(server_list) == 0:
            return createJsonReponse('请配置mock平台配置相应的路由')

        # 检查 api_router
        router_list = Api_Route.objects.filter(path=api_router,server=server_list[0])
        if len(router_list) == 0:
            return createJsonReponse('请配置mock平台配置相应的路由')

        # 检查api_response
        reponse_list = Response.objects.filter(router=router_list[0])
        if len(reponse_list) == 0:
            return createJsonReponse('请配置mock平台配置相应的路由')

        # 在响应列表中随机挑选一个
        repone = reponse_list[random.randint(0,len(reponse_list)-1)]
        delay = repone.delay
        result = repone.json_result
        time.sleep(delay)
        return createJsonReponse(result)


class Server_list(View):
    def get(self,request):
        all_server = Server.objects.all()

        return  render(request,'mock/base.html',{'all_server':all_server})

class Add_server(View):
    def get(self,request):
        addserver_form = ServeraddForm()
        return render(request,'mock/add_server.html',{'addserver_form':addserver_form})

    def post(self,request):
        addserver_form = ServeraddForm(request.POST)
        if addserver_form.is_valid():
            name = addserver_form.cleaned_data['name']
            path = addserver_form.cleaned_data['path']

            # server_path = Server.objects.get(path=path)
            # if server_path:
            #     return render(request,'mock/add_server.html',{'msg':'serverPath is already exist'})
            # else:
            server_profile = Server()
            server_profile.name = name
            server_profile.path = path
            server_profile.save()
            return redirect(reverse('server_list'))
        else:
            return render(request,'mock/add_server.html',{'addserver_form':addserver_form})

class Router_list(View):
    def get(self,request):
        all_router = Api_Route.objects.all()
        return render(request,'mock/route.html',{'all_router':all_router})


class Add_router(View):
    def get(self,request):
        addrouter_form = RouteraddForm()
        return render(request,'mock/add_router.html',{'addrouter_form':addrouter_form})

    def post(self,request):
        addrouter_form = RouteraddForm(request.POST)
        if addrouter_form.is_valid():
            name = addrouter_form.cleaned_data['name']
            path = addrouter_form.cleaned_data['path']
            server = addrouter_form.cleaned_data['server']
            server_name = Server.objects.get(name=server)
            # server_path = Server.objects.get(path=path)
            # if server_path:
            #     return render(request,'mock/add_server.html',{'msg':'serverPath is already exist'})
            # else:
            router_profile = Api_Route()
            router_profile.name = name
            router_profile.path = path
            router_profile.server = server_name
            router_profile.save()
            return redirect(reverse('router_list'))
        else:
            return render(request,'mock/add_router.html',{'addrouter_form':addrouter_form})


class Reponse_list(View):
    def get(self,request):
        all_reponse = Response.objects.all()
        return render(request,'mock/reponse.html',{'all_reponse':all_reponse})

class Add_Response(View):
    def get(self,request):
        addresponse = ResponseaddForm()
        return render(request,'mock/add_response.html',{'addresponse':addresponse})
    def post(self,request):
        addresponse = ResponseaddForm(request.POST)
        if addresponse.is_valid():
            name = addresponse.cleaned_data['name']
            json_result = addresponse.cleaned_data['json_result']
            delay = addresponse.cleaned_data['delay']
            router = addresponse.cleaned_data['router']
            router_name = Api_Route.objects.get(name=router)

            # server_path = Server.objects.get(path=path)
            # if server_path:
            #     return render(request,'mock/add_server.html',{'msg':'serverPath is already exist'})
            # else:
            response_profile = Response()
            response_profile.name = name
            response_profile.json_result = json_result
            response_profile.delay = delay
            response_profile.router = router_name
            response_profile.save()
            return redirect(reverse('response_list'))
        else:
            return render(request,'mock/editresponse.html',{'addresponse':addresponse})

class Edit_info(View):
    def get(self,request,id):
        server_obj = Server.objects.get(id=id)
        return render(request,'mock/editInfo.html',{'server_obj':server_obj})

    def post(self,request,id):
        editserver_form = EditServerForm(request.POST)
        if editserver_form.is_valid():
            name = editserver_form.cleaned_data['name']
            path = editserver_form.cleaned_data['path']

            server_path = Server.objects.get(path=path)
            if server_path:
                return render(request, 'mock/editInfo.html', {'msg': 'serverPath is already exist'})
            else:
                server_profile = Server.objects.get(pk=id)
                server_profile.name = name
                server_profile.path = path
                server_profile.save()
            return redirect(reverse('server_list'))
        else:
            return render(request, 'mock/editInfo.html', {'editserver_form': editserver_form})

class Delete_info(View):

    def get(self,request,id):
        server_pro = Server.objects.get(id=id)
        return render(request,'mock/deleteInfo.html',{'server_pro':server_pro})

    def post(self,request,id):
        server_pro = Server.objects.get(pk=id)
        server_pro.delete()
        return redirect(reverse('server_list'))


class Edit_router(View):
    def get(self,request,id):
        router_obj = Api_Route.objects.get(id=id)
        return render(request,'mock/editrouter.html',{'router_obj':router_obj})

    def post(self, request,id):
        addrouter_form = RouteraddForm(request.POST)
        if addrouter_form.is_valid():
            name = addrouter_form.cleaned_data['name']
            path = addrouter_form.cleaned_data['path']
            server = addrouter_form.cleaned_data['server']
            server_name = Server.objects.get(name=server)
            # server_path = Server.objects.get(path=path)
            # if server_path:
            #     return render(request,'mock/add_server.html',{'msg':'serverPath is already exist'})
            # else:
            router_profile = Api_Route.objects.get(pk=id)
            router_profile.name = name
            router_profile.path = path
            router_profile.server = server_name
            router_profile.save()
            return redirect(reverse('router_list'))
        else:
            return render(request, 'mock/add_router.html', {'addrouter_form': addrouter_form})

class Delete_router(View):

    def get(self,request,id):
        router_obj = Api_Route.objects.get(id=id)
        return render(request,'mock/deleterouter.html',{'router_obj':router_obj})

    def post(self,request,id):
        router_profile = Api_Route.objects.get(pk=id)
        router_profile.delete()
        return redirect(reverse('router_list'))



class Edit_response(View):
    def get(self,request,id):
        response_obj = Response.objects.get(id=id)
        return render(request,'mock/editresponse.html',{'response_obj':response_obj})

    def post(self, request,id):
        addresponse = ResponseaddForm(request.POST)
        if addresponse.is_valid():
            name = addresponse.cleaned_data['name']
            json_result = addresponse.cleaned_data['json_result']
            delay = addresponse.cleaned_data['delay']
            router = addresponse.cleaned_data['router']
            router_name = Api_Route.objects.get(name=router)

            # server_path = Server.objects.get(path=path)
            # if server_path:
            #     return render(request,'mock/add_server.html',{'msg':'serverPath is already exist'})
            # else:
            response_profile = Response.objects.get(pk=id)
            response_profile.name = name
            response_profile.json_result = json_result
            response_profile.delay = delay
            response_profile.router = router_name
            response_profile.save()
            return redirect(reverse('response_list'))
        else:
            return render(request, 'mock/editresponse.html', {'addresponse': addresponse})

class Delete_response(View):

    def get(self,request,id):
        response_obj = Response.objects.get(id=id)
        return render(request,'mock/deleteresponse.html',{'response_obj':response_obj})

    def post(self,request,id):
        router_profile = Response.objects.get(pk=id)
        router_profile.delete()
        return redirect(reverse('response_list'))







